<?php
/**
 * Created by PhpStorm.
 * User: frankpian
 * Date: 17-12-9
 * Time: 下午5:48
 */

use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class FlightdataController extends CloudControllerBase
{


    /****************************    电池信息   ****************************************************/

    public function listBatteryAction(){
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $paramQueryList = json_decode($this->getPost("filter_list"), true);
                $viewType=$paramQueryList["view_type"];
                $contactInfo="(select CONCAT('持有单位:',name,'<br>手机号:',phone) as contact_info,uas_serial_id from plane)";
                $tableSql4StatRe="(
                            SELECT
                                re2.*
                            FROM
                                (
                                    SELECT
                                        max(id) AS reid
                                    FROM
                                        battery_record
                                    GROUP BY
                                        battery_no
                                ) AS re1
                            INNER JOIN battery_record AS re2 ON re1.reid = re2.id
                        ) AS re";
                $tableSql4Column="
                            info.battery_no,
                            info.created_at,
                            info.uas_serial_id,
                            re.battery_no as re_battery_no,
                            re.battery_charge_discharge_times,
                            re.log_time_value,
                            re.log_mil_value,
                            re.created_at as last_time,
                            re.flight_task_name,
                            re.uas_serial_id as last_uas_serial_id,
                            p1.contact_info as origin_contact_info,
                            p2.contact_info as last_contact_info
                            ";
                $tableSql1=
                    "(
                        SELECT
                            $tableSql4Column
                        FROM
                            battery_info AS info
                        LEFT JOIN $contactInfo as p1 on info.uas_serial_id=p1.uas_serial_id
                        RIGHT OUTER JOIN $tableSql4StatRe ON re.battery_no = info.battery_no
                        LEFT JOIN $contactInfo as p2 on re.uas_serial_id=p2.uas_serial_id
                    )";
                $tableSql2 =
                    "(
                        SELECT
                            $tableSql4Column
                        FROM
                            battery_info AS info
                        LEFT JOIN $contactInfo as p1 on info.uas_serial_id=p1.uas_serial_id
                        LEFT JOIN $tableSql4StatRe ON re.battery_no = info.battery_no
                        LEFT JOIN $contactInfo as p2 on re.uas_serial_id=p2.uas_serial_id
                    )";
                switch ($viewType){
                    case 1:{
                        $table=$tableSql1;
                    };break;
                    case 2:{
                        $table=$tableSql2;
                    };break;
                    case 3:{
                        $table="(select * from $tableSql1 as t1 union select * from $tableSql2 as t2)";
                    };break;
                }

                $this->postQueryByPage(array(
                    "battery_no" => "出厂电池编号",
                    "created_at" => "出厂日期",
                    "uas_serial_id" => "出厂飞机编号",
                    "origin_contact_info"=>"出厂飞机联系",
                    "re_battery_no" => "统计电池编号",
                    "battery_charge_discharge_times" => "充放电次数",
                    "log_time_value" => "总飞行时间",
                    "log_mil_value" => "总飞行里程",
                    "last_uas_serial_id"=>"最后飞行飞机编号",
                    "last_contact_info"=>"最后飞行飞机联系",
                    "last_time"=>"最后飞行时间",
                    "flight_task_name"=>"最后飞行任务"
                ), $table
                    , array(
                        ["last_uas_serial_id", "like", "%", "%"],
                        ["re_battery_no", "like", "%", "%"],
                        ["battery_no", "like", "%", "%"],
                        ["origin_contact_info", "origin", "%", "%"],
                        ["uas_serial_id", "like", "%", "%"],
                        ['battery_time_start', '>=', '', '', "battery_charge_discharge_times"],
                        ['battery_time_end',  '<=', '', '', "battery_charge_discharge_times"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }


    }

    /****************************    数据处理项目管理   ****************************************************/
    public function listDataProjectAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT D.*, user.phone FROM data_project AS D
                    LEFT JOIN user ON D.user_id=user.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "phone" => "电话",
                    "local_id" => "LocalID",
                    "project_name" => "项目名称",
                    "operator" => "操作人",
                    "date" => "日期",
                    "description" => "描述",
                    "height" => "高度",
                    "thumbnail" => "Thumbnail",
                    "created_at" => "创建时间",
                    "updated_at" => "更新时间",
                    "version" => "版本"
                ), $table
                    , array(
                        ["id", "="],
                        ["phone", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["project_name", "like", "%", "%"],
                        ["operator", "like", "%", "%"],
                        ["version", "="],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailDataProjectAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT D.* FROM data_project AS D
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "LocalID", ""],
                ["project_name", "项目名称", ""],
                ["operator", "操作人", ""],
                ["date", "日期", ""],
                ["coordinate_id", "CoordinateID", ""],
                ["coordinate_type", "CoordinateType", ""],
                ["coordinate_name", "CoordinateName", ""],
                ["coordinate_description", "CoordinateDescription", ""],
                ["description", "版本描述", "", true, "", "text-area", "3"],
                ["height", "高度", ""],
                ["thumbnail", "ThumbNail", ""],
                ["created_at", "创建时间", ""],
                ["updated_at", "更新时间", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    相机数据管理   ****************************************************/
    public function listDataCameraAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT c.*, d.local_id AS project_local_id FROM data_camera AS c
                    LEFT JOIN data_project AS d ON c.project_id=d.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "project_id" => "项目ID",
                    "project_local_id" => "项目LocalID",
                    "local_id" => "LocalID",
                    "name" => "名称",
                    "width" => "Width",
                    "height" => "Height"
                ), $table
                    , array(
                        ["id", "="],
                        ["project_id", "="],
                        ["project_local_id", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["name", "like", "%", "%"],
                        ["width", "="],
                        ["height", "="]
                    ),"id","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailDataCameraAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT * FROM data_camera
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "LocalID", ""],
                ["name", "Name", ""],
                ["width", "Width", ""],
                ["height", "Height", ""],
                ["ccdwidth", "CcdWidth", ""],
                ["ccdheight", "CcdHeight", ""],
                ["focallength", "FocalLength", ""],
                ["x0", "X0", ""],
                ["y0", "Y0", ""],
                ["distortion_type", "Distortion Type", ""],
                ["k1", "K1", ""],
                ["k1", "K2", ""],
                ["k3", "K3", ""],
                ["p1", "P1", ""],
                ["p2", "P2", ""],
                ["alpha", "Alpha", ""],
                ["beta", "Beta", ""],
                ["n1", "N1", ""],
                ["n2", "N2", ""],
                ["n3", "N3", ""],
                ["n4", "N4", ""],
                ["n5", "N5", ""],
                ["delay_time", "Delay Time", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    影像信息管理   ****************************************************/
    public function listDataImageAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT c.*, d.local_id AS project_local_id FROM data_image AS c
                    LEFT JOIN data_project AS d ON c.project_id=d.id)";
                $this->postQueryByPage(array(
                    "id" => "sever ID",
                    "project_id" => "server project id",
                    "project_local_id" => "project id",
                    "local_id" => "id",
                    "name" => "name",
                    "path" => "path",
                ), $table
                    , array(
                        ["id", "="],
                        ["project_id", "="],
                        ["project_local_id", "="],
                        ["local_id", "="],
                        ["name", "="],
                        ["path", "="]
                    ),"id","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailDataImageAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT D.* FROM data_image AS D
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "LocalID", ""],
                ["name", "Name", ""],
                ["path", "Path", ""],
                ["x", "X", ""],
                ["y", "Y", ""],
                ["z", "Z", ""],
                ["omega", "Omega", ""],
                ["kappa", "Kappa", ""],
                ["new_x", "New X", ""],
                ["new_y", "New Y", ""],
                ["new_z", "New_Z", ""],
                ["new_omega", "New Omega", ""],
                ["new_phi", "New Phi", ""],
                ["new_kappa", "New_Kappa", ""],
                ["strip_id", "Strip ID", ""],
                ["camera_id", "Camera_ID", ""],
                ["id", "", "", false]
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    质检报告管理 ****************************************************/
    public function listDataReportAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT c.*, d.local_id AS project_local_id FROM data_report AS c
                    LEFT JOIN data_project AS d ON c.project_id=d.id)";
                $this->postQueryByPage(array(
                    "id" => "sever ID",
                    "project_id" => "server project id",
                    "project_local_id" => "project id",
                    "local_id" => "id",
                    "date" => "date",
                    "content" => "content",
                ), $table
                    , array(
                        ["id", "="],
                        ["project_id", "="],
                        ["project_local_id", "="],
                        ["local_id", "="],
                        ['date_start', '>=', '', '', "date"],
                        ['date_end', '<=', '', '', "date"],
                        ["content", "="]
                    ),"date desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailDataReportAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT * FROM data_report
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "Local ID", ""],
                ["date", "Date", ""],
                ["content", "Content", ""],
                ["id", "", "", false]
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /**************************** 飞行记录管理 ****************************************************/


    public function downloadFlightLogAction(){
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $this->checkRequestParams(array(
            array(
                "key" => "local_id",
                "type" => "presence",
                "message" => "local_id为空"),
        ),true);

        $local_id=$this->getQuery("local_id");
        $flightData=$this->fetchOne("select id,created_at from flight_mission where local_id='$local_id'",60*10);

        if($flightData){
            $flight_mission_id=intval($flightData["id"]);
            //$created_at=strtotime($flightData["created_at"]);
            $data=$this->dbFlightLogProxy->fetchAll("flight_mission_id=$flight_mission_id");
            if($data){

                $name="data_$flight_mission_id.tlog";
                $filePath="./../app/cache/";
                $file=fopen($filePath.$name,"w");
                foreach ($data as $item){
                    $msgData=$item["message"];
                    if(!empty($msgData)&&!empty($item["created_str"])){

                        $pos=strrpos($item["created_str"],":");
                        if($pos===false){
                        }else{
                            $dateStr=substr($item["created_str"],0,$pos);
                            $millsecond=intval(substr($item["created_str"],$pos+1));
                            $createdTime=(strtotime($dateStr)*1000+$millsecond)*1000;
                            $hexStringValue = base_convert($createdTime, 10, 16);
                            $hexStringValue = str_pad($hexStringValue, 16, '0', STR_PAD_LEFT);
                            $packed64bitInteger = hex2bin($hexStringValue);
                            fwrite($file,$packed64bitInteger);
                            fwrite($file,base64_decode($msgData));
                        }

                    }
                }
                if($file){
                    fclose($file);
                }
                $this->download_by_path($filePath,$name,$name);
                unlink($filePath.$name);
            }else{
                $this->returnError("没有相关数据");
            }
        }else{
            $this->returnError("没有对应的飞行架次");
        }

    }

    public function listFlightMissionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "(SELECT
	uas.uas_serial_id,
	mis.local_id,
	survey_area_name,
	uas.created_at,
	mis.flight_task_id to_flight_task_id,
	mis.project_id to_project_id
FROM
	flight_mission AS mis
INNER JOIN (
	SELECT
		*
	FROM
		uas_status
	GROUP BY
		flight_mission_id
) AS uas ON uas.flight_mission_id = mis.id)";

                $this->postQueryByPage(array(
                    "uas_serial_id" => "飞机序列号",
                    "local_id" => "任务架次",
                    "to_project_id" => "项目名称",
                    "to_flight_task_id" => "任务名称",
                    "survey_area_name" => "测区名称",
                    "created_at" => "创建时间",
                ), $tableName, array(
                    ["uas_serial_id", "like", "%", "%"],
                    ['local_id', 'like', '%', '%'],
                    ['to_flight_task_id', 'like', '%', '%'],
                    ['to_project_id', 'like', '%', '%'],
                    ['survey_area_name', 'like', '%', '%'],
                    ['created_at_start', '>=', '', '', "created_at"],
                    ['created_at_end', '<=', '', '', "created_at"]
                ), "created_at desc", "local_id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailFlightMissionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $local_id=$this->getQuery("local_id");
        if(empty($keyId)){
            $where="local_id='$local_id'";

        }else{
            $where="id=$keyId";
        }
        $this->generateDetailData(array(
            "table" => "flight_mission",
            "column" => array(
                ["local_id", "Local ID", ""],
                ["created_at", "Created At", ""],
                ["flight_task_id", "Flight Task ID", ""],
                ["project_id", "Project ID", ""],
                ["survey_area_name", "Survey Area Name", ""],
                ["block_type", "Block Type", ""],
                ["survey_area_coordinate_points", "Survey Area Coordinate Points", "", true, "", "text-area", "2"],
                ["survey_lowest_altitude", "Survey Lowest Altitude", ""],
                ["survey_highest_altitude", "Survey Highest Altitude", ""],
                ["survey_average_altitude", "Survey Average Altitude", ""],
                ["camera_type", "Camera Type", ""],
                ["camera_pixel_size", "Camera Pixel Size", ""],
                ["camera_focal_length", "Camera Focal Length", ""],
                ["camera_image_width", "Camera Image Width", ""],
                ["camera_image_height", "Camera Image Height", ""],
                ["camera_placement_angle", "Camera Placement Angle", ""],
                ["longitudinal_overlap", "Longitudinal Overlap", ""],
                ["lateral_overlap", "Lateral Overlap", ""],
                ["average_ground_resolution", "Average Ground Resolution", ""],
                ["auto_route_begin_exp_num", "Auto Route Begin Exp Num", ""],
                ["auto_route_end_exp_num", "Auto Route End Exp Num", ""],
                ["auto_route_range_exp_dist", "Auto Route Range Exp Dist", ""],
                ["entry_direction", "Entry Direction", ""],
                ["home_lng", "Home Lng", ""],
                ["home_lat", "Home Lat", ""],
                ["home_elevation", "Home Elevation", ""],
                ["landing_method", "Landing Method", ""],
                ["landing_angle", "Landing Angle", ""],
                ["flight_relative_altitude", "Flight Relative Altittude", ""],
                ["flight_altitude", "Flight Altitude", ""],
                ["flight_interval", "Flight Interval", ""],
                ["take_pic_interval", "Take Pic Interval", ""],
                ["work_area", "Work Area", ""],
                ["work_time", "Work Time", ""],
                ["default_air_speed", "Default Air Speed", ""],
                ["high_gsd", "High Gsd", ""],
                ["high_longitudinal_overlap", "High Longitudinal Overlap", ""],
                ["high_lateral_overlap", "High Lateral Overlap", ""],
                ["low_gsd", "Low Gsd", ""],
                ["low_longitudinal_overlap", "Low Longitudinal Overlap", ""],
                ["flight_task_created_at", "Flight Task Created AT", ""],
                ["task_coordinate_points", "Task Coordinate Points", "", true, "", "text-area", "3"],
                ["task_coordinate_waypoints", "Task Coordinate Waypoints", "", true, "", "text-area", "3"],
                ["flight_check_begin_at", "Flight Check Begin At", ""],
                ["nickname", "Nick Name", ""],
                ["phone", "Phone", ""],
                ["check_speed_height_gyro", "Check Speed Height Gyro", ""],
                ["check_gps_battery_sansor", "Check Gps Battery Sansor", ""],
                ["check_upload_waypoint", "Check Upload Waypoint", ""],
                ["check_take_picture", "Check Take Picture", ""],
                ["check_ok", "Check Ok", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["voyage", "里程", ""],
                ["voyage_duration", "飞行时间(秒)", ""],
                ["id", "", "", false]
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where"=>$where
        ));
    }

    /****************************    起降状态管理   ****************************************************/
    public function listUasStatusAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT U.*, F.local_id AS flight_local_id FROM uas_status AS U
                    LEFT JOIN flight_mission AS F ON U.flight_mission_id=F.id)";
                $this->postQueryByPage(array(
                    "id" => "server ID",
                    "flight_local_id" => "飞行任务ID",
                    "local_id" => "ID",
                    "uas_serial_id" => "飞机序列号",
                    "is_takeoff" => "降落",
                    "auto_pilot_firmware_version" => "飞控固件版本",
                    "radio_firmware_version" => "电台固件版本",
                    "imu3_state" => "3路IMU传感器状态",
                    "created_at" => "创建时间"
                ), $table
                    , array(
                        ["id", "="],
                        ["phone", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["project_name", "like", "%", "%"],
                        ["operator", "like", "%", "%"],
                        ["version", "="],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailUasStatusAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT U.*, F.local_id AS flight_local_id FROM uas_status AS U
            LEFT JOIN flight_mission AS F ON U.flight_mission_id=F.id
            WHERE U.id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["flight_mission_id", "Mission Server ID", ""],
                ["flight_local_id", "飞行任务ID", ""],
                ["local_id", "ID", ""],
                ["created_at", "记录时间", ""],
                ["uas_serial_id", "飞机序列号", ""],
                ["auto_pilot_firmware_version", "飞控固件版本", ""],
                ["is_takeoff", "降落", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["uas_odometer_value", "当前飞机里程表数值(公里)", ""],
                ["battery_no", "电池编号", ""],
                ["battery_capacity", "当前得电池容量(0~100)", ""],
                ["battery_voltage", "当前电池电压(V)", ""],
                ["battery_current", "当前电池电流(mA)", ""],
                ["imu3_state", "3路传感器状态(0:正常 n:n路故障)", ""],
                ["battery_charge_discharge_times", "智能电池充放电次数", ""],
                ["opening_parachute_times", "开伞次数", ""],
                ["flight_sorties", "起降架次", ""],
                ["steering_engine_operate_times", "舵机动作次数", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    飞行日志管理   ****************************************************/
    public function listFlightLogAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT F.* FROM flight_mission
                    LEFT JOIN flight_mission ON F.)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "flight_local_id" => "飞行任务ID",
                    "local_id" => "ID",
                    "uas_serial_id" => "飞机序列号",
                    "is_takeoff" => "降落",
                    "auto_pilot_firmware_version" => "飞控固件版本",
                    "radio_firmware_version" => "电台固件版本",
                    "imu3_state" => "3路IMU传感器状态",
                    "created_at" => "创建时间"
                ), $table
                    , array(
                        ["id", "="],
                        ["phone", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["project_name", "like", "%", "%"],
                        ["operator", "like", "%", "%"],
                        ["version", "="],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailFlightLogAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT U.*, F.local_id AS flight_local_id FROM uas_status AS U
            LEFT JOIN flight_mission AS F ON U.flight_mission_id=F.id
            WHERE U.id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["flight_mission_id", "Mission Server ID", ""],
                ["flight_local_id", "飞行任务ID", ""],
                ["local_id", "ID", ""],
                ["created_at", "记录时间", ""],
                ["uas_serial_id", "飞机序列号", ""],
                ["auto_pilot_firmware_version", "飞控固件版本", ""],
                ["is_takeoff", "降落", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["uas_odometer_value", "当前飞机里程表数值(公里)", ""],
                ["battery_no", "电池编号", ""],
                ["battery_capacity", "当前得电池容量(0~100)", ""],
                ["battery_voltage", "当前电池电压(V)", ""],
                ["battery_current", "当前电池电流(mA)", ""],
                ["imu3_state", "3路传感器状态(0:正常 n:n路故障)", ""],
                ["battery_charge_discharge_times", "智能电池充放电次数", ""],
                ["opening_parachute_times", "开伞次数", ""],
                ["flight_sorties", "起降架次", ""],
                ["steering_engine_operate_times", "舵机动作次数", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    POS数据管理   ****************************************************/
    public function listDataPosAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT P.*, F.local_id AS flight_local_id FROM pos_data AS P
                    LEFT JOIN flight_mission AS F ON P.flight_mission_id=F.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "flight_local_id" => "飞行任务ID",
                    "img_idx" => "图像索引号",
                    "lng" => "经度",
                    "lat" => "纬度",
                    "alt_msl" => "绝对海拔高度",
                    "alt_rel" => "相对HOME点高度",
                    "roll" => "相机滚转角",
                    "pitch" => "相机俯仰角",
                    "yaw" => "相机偏航角",
                    "created_at" => "拍照时间"
                ), $table
                    , array(
                        ["id", "="],
                        ["flight_local_id", "like", "%", "%"],
                        ["img_idx", "="],
                        ["lng", "like", "%", "%"],
                        ["lat", "like", "%", "%"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailDataPosAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT * FROM pos_data
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["img_idx", "图像索引号", ""],
                ["lng", "经度", ""],
                ["lat", "纬度", ""],
                ["alt_msl", "绝对海拔高度", ""],
                ["alt_rel", "相对HOME点高度", ""],
                ["roll", "相机滚转角", ""],
                ["pitch", "相机俯仰角", ""],
                ["yaw", "拍照时间", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    飞行项目管理   ****************************************************/
    public function listFlightProjectAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT p.*, user.phone FROM project AS p
                    LEFT JOIN user ON p.user_id=user.id)";
                $this->postQueryByPage(array(
                    "id" => "Server ID",
                    "phone" => "电话",
                    "local_id" => "ID",
                    "project_name" => "项目名称",
                    "created_at" => "上传时间",
                    "updated_at" => "当前版本修改时间",
                    "version" => "版本号",
                    "is_removed" => "是否已删除"
                ), $table
                    , array(
                        ["id", "="],
                        ["phone", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["project_name", "like", "%", "%"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"],
                        ['updated_at_start', '>=', '', '', "updated_at"],
                        ['updated_at_end', '<=', '', '', "updated_at"],
                        ["version", "="],
                        ["is_removed", "="],
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailFlightProjectAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT p.*, user.nickname FROM project AS p
            LEFT JOIN user ON p.user_id=user.id
            WHERE p.id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "ID", ""],
                ["project_name", "项目名称", ""],
                ["created_at", "上传时间", ""],
                ["updated_at", "当前版本修改时间", ""],
                ["version", "版本号", ""],
                ["is_removed", "是否已删除", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["center_position_lng", "经度", ""],
                ["center_position_lat", "纬度", ""],
                ["map_scale", "地图放大倍数", ""],
                ["user_id", "用户ID", ""],
                ["nickname", "用户名", ""],
                ["id", "", "", false]
            ),
            "title" => "Server ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    飞行区域管理   ****************************************************/
    public function listSurveyBlockAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT S.*, project.local_id AS project_local_id FROM survey_block AS S
                    LEFT JOIN project ON S.project_id=project.id)";
                $this->postQueryByPage(array(
                    "id" => "Server ID",
                    "project_id" => "Server Project ID",
                    "local_id" => "ID",
                    "project_local_id" => "Project ID",
                    "created_at" => "Created At",
                    "updated_at" => "Updated At",
                    "survey_area_guid" => "Survey Area Guid",
                    "survey_area_name" => "Survey Area Name",
                    "is_return" => "Is Return",
                    "plane_type" => "Plane Type",
                ), $table
                    , array(
                        ["id", "="],
                        ["project_id", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["project_local_id", "like", "%", "%"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"],
                        ['updated_at_start', '>=', '', '', "updated_at"],
                        ['updated_at_end', '<=', '', '', "updated_at"],
                        ["is_return", "="],
                        ["plane_type", "="],
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailSurveyBlockAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT * FROM survey_block
            WHERE id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "ID", ""],
                ["local_id", "Local Id", ""],
                ["created_at", "Created At", ""],
                ["updated_at", "Updated At", ""],
                ["survey_area_guid", "Survey Area Guid", ""],
                ["survey_area_name", "Survey Area Name", ""],
                ["import_flag", "Import Flag", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["block_type", "Block Type", ""],
                ["plane_type", "Plane Type", ""],
                ["split_flag", "Split Flag", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["split_direction", "Split Direction", ""],
                ["survey_area_coordinate_points", "Survey Area Coordinate Points", "", true, "", "text-area", "2"],
                ["survey_lowest_altitude", "Survey Lowest Altitude", ""],
                ["survey_highest_altitude", "Survey Highest Altitude", ""],
                ["survey_average_altitude", "Survey Average Altitude", ""],
                ["camera_type", "Camera Type", ""],
                ["camera_pixel_size", "Camera Pixel Size", ""],
                ["camera_focal_length", "Camera Focal Length", ""],
                ["camera_image_width", "Camera Image Width", ""],
                ["camera_image_height", "Camera Image Height", ""],
                ["camera_placement_angle", "Camera Placement Angle", ""],
                ["longitudinal_overlap", "Longitudinal Overlap", ""],
                ["lateral_overlap", "Lateral Overlap", ""],
                ["average_ground_resolution", "Average Ground Resolution", ""],
                ["auto_route_begin_exp_num", "Auto Route Begin Exp Num", ""],
                ["auto_route_end_exp_num", "Auto Route End Exp Num", ""],
                ["auto_route_range_exp_dist", "Auto Route Range Exp Dist", ""],
                ["entry_direction", "Entry Direction", ""],
                ["home_lng", "Home Lng", ""],
                ["home_lat", "Home Lat", ""],
                ["landing_method", "Landing Method", ""],
                ["landing_angle", "Landing Angle", ""],
                ["flight_relative_altitude", "Flight Relative Altitude", ""],
                ["flight_altitude", "Flight Altitude", ""],
                ["flight_interval", "Flight Interval", ""],
                ["take_pic_interval", "Take Pic Interval", ""],
                ["work_area", "Work Area", ""],
                ["work_time", "Work Time", ""],
                ["default_air_speed", "Default Air Speed", ""],
                ["high_gsd", "High Gsd", ""],
                ["high_longitudinal_overlap", "High Longitudinal Overlap", ""],
                ["high_lateral_overlap", "High Lateral Overlap", ""],
                ["low_gsd", "Low Gsd", ""],
                ["is_return", "Is Return", "", true, "", "select", array("是" => 1, "否" => 0)],
                ["low_longitudinal_overlap", "Low Longitudinal Overlap", ""],
                ["low_lateral_overlap", "Low Lateral Overlap", ""],
                ["left_offset_distance", "Left Offset Distance", ""],
                ["right_offset_distance", "Right Offset Distance", ""],
                ["id", "", "", false]
            ),
            "title" => "Server ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    飞行任务管理   ****************************************************/
    public function listFlightTaskAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT f.*, s.local_id AS survey_local_id FROM flight_task AS f
                    LEFT JOIN survey_block AS s ON f.survey_block_id=s.id)";
                $this->postQueryByPage(array(
                    "id" => "Server ID",
                    "survey_block_id" => "Server Block ID",
                    "local_id" => "ID",
                    "survey_local_id" => "Survey Block ID",
                    "flight_task_guid" => "Flight Task Guid",
                    "flight_task_name" => "Flight Task Name",
                ), $table
                    , array(
                        ["id", "="],
                        ["survey_block_id", "like", "%", "%"],
                        ["local_id", "like", "%", "%"],
                        ["survey_local_id", "like", "%", "%"],
                        ["flight_task_guid", "like", "%", "%"],
                        ["flight_task_name", "like", "%", "%"]
                    ),"id","id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }

    public function detailFlightTaskAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $keyId = intval($this->getQuery("id"));
        $sql = "(SELECT f.*, s.local_id AS survey_local_id FROM flight_task AS f
                    LEFT JOIN survey_block AS s ON f.survey_block_id=s.id
            WHERE f.id=$keyId)";
        $this->generateDetailData(array(
            "table" => $sql,
            "column" => array(
                ["local_id", "Local ID", ""],
                ["survey_local_id", "Survey Block ID", ""],
                ["created_at", "Created At", ""],
                ["flight_task_guid", "Flight Task Guid", ""],
                ["flight_task_name", "Flight Task Name", ""],
                ["task_coordinate_points", "Task Coordinate Points", "", true, "", "text-area", "3"],
                ["task_coordinate_waypoints", "Task Coordinate Waypoints", "", true, "", "text-area", "3"],
                ["photo_count", "Photo Count", ""],
                ["total_mileage", "Total Mileage", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => "id=$keyId",
        ));
    }

    /****************************    数据记录器   ****************************************************/
    public function listDataRecorderAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT created_at,flight_mission_id,uas_serial_id FROM flight_data GROUP BY flight_mission_id)";
                $this->postQueryByPage(array(
                    "flight_mission_id" => "Flight Mission ID",
                    "uas_serial_id" => "飞机序列号",
                    "created_at" => "创建时间"
                ), $table
                    , array(
//                        ["id", "="],
                        ["flight_mission_id", "like", "%", "%"],
                        ["uas_serial_id", "like", "%", "%"],
//                        ['lng_start', '>=', '', '', "lng"],
//                        ['lng_end', '<=', '', '', "lng"],
//                        ['lat_start', '>=', '', '', "lat"],
//                        ['lat_end', '<=', '', '', "lat"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","flight_mission_id");
            };
                break;
        }
    }

    public function detailDataRecorderAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_LIST: {
                $flight_mission_id = $this->getPost("id");
                $table = "(SELECT * FROM flight_data WHERE flight_mission_id = '".$flight_mission_id."')";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "lng" => "经度",
                    "lat" => "纬度",
                    "alt" => "高度",
                    "created_at" => "创建时间"
                ), $table
                    , array(
//                        ["id", "="],
//                        ["flight_mission_id", "like", "%", "%"],
//                        ["uas_serial_id", "like", "%", "%"],
//                        ['lng_start', '>=', '', '', "lng"],
//                        ['lng_end', '<=', '', '', "lng"],
//                        ['lat_start', '>=', '', '', "lat"],
//                        ['lat_end', '<=', '', '', "lat"],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","flight_mission_id");
            };
                break;
        }
    }

    public function filedItemChanged($table, $name, $value)
    {
        switch($name){
            case "is_takeoff": {
                if ($value=="1"){
                    return "<span style='font-weight:bold; color:#ffffff; background: #00db1c; border-radius:4px'>&nbsp;是&nbsp;</span>";
                }else{
                    return "<span style='font-weight:bold; color:#ffffff; background: #db0006; border-radius:4px'>&nbsp;否&nbsp;</span>";
                }
            };
                break;
            case "is_return":
            case "is_removed": {
                if ($value == '1'){
                    return "<span style='font-weight:bold; color:#ffffff; background: #00db1c; border-radius:4px'>&nbsp;是&nbsp;</span>";
                }elseif ($value == '0'){
                    return "<span style='font-weight:bold; color:#ffffff; background: #db0006; border-radius:4px'>&nbsp;否&nbsp;</span>";
                }
            };
                break;
            case "to_flight_task_id":{
                if(!empty($value)){
                    $taskName=$this->fetchColumn("select flight_task_name from flight_task where local_id='$value'",100);
                    if(!empty($taskName)){
                        $value=$taskName;
                    }else{
                        $value="任务暂未同步";
                    }
                }else{
                    $value="";
                }
            };break;
            case "to_project_id":{
                if(!empty($value)){
                    $projectName=$this->fetchColumn("select project_name from project where local_id='$value'",100);
                    if(!empty($projectName)){
                        $value=$projectName;
                    }else{
                        $value="项目暂未同步";
                    }
                }else{
                    $value="";
                }
            };break;
            case "origin_contact_info":
            case "last_contact_info":
            case "battery_no":
            case "re_battery_no":
            case "created_at":
            case "uas_serial_id":
            case "last_uas_serial_id":
            case "last_time":
            case "flight_task_name":
            case "log_mil_value":
            case "log_time_value":
            case "battery_charge_discharge_times":{
                if(empty($value)){
                    $value="";
                }
            };break;
        }
        return $value;
    }
}